<template>
    <div style="line-height: 40px;font-size: 20px;line-height: 60px;font-size: 22px;width: 210mm; margin: 0 auto;background-color: #f5f7fa;padding:0px 50px;">

        <div style="display: flex;justify-content: space-between;">
            <span>
                <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
            </span>
            <span>
                <el-button type="success" icon="el-icon-check" v-if="!isView" @click="saveData">保存</el-button>
                <el-button type="primary" icon="el-icon-menu" @click="goToList">列表</el-button>
                <!-- <button @click="printToPDF">打印PDF</button> -->
                <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
        </div>
        <div style="text-align: left;margin: 0px auto;" class="agreement-wrapper">
            <h2 style="text-align: center;">协商解除劳动合同协议书一</h2>
            <hr style="border-color: black; width: 110%;margin: 30px -40px;">
            <div class="form-group">
                <label style="font-weight: bold;">甲方：</label>
                <input v-model="agreementData.aparty" :disabled="isView">
            </div>
            <div class="form-group">
                <label style="font-weight: bold;">乙方：</label>
                <input v-model="agreementData.bparty" :disabled="isView">&emsp;&emsp;&emsp;
                <label style="font-weight: bold;">（身份证号码：</label>
                <input style="border-bottom: 1px solid;" v-model="agreementData.idNumber" :disabled="isView">
                <label>）</label>
            </div>
            <div class="clause">
                <p style=" padding-left: -30px;">一、
                    <el-date-picker v-model="agreementData.startDate" type="date" :disabled="isView"
                        value-format="yyyy-MM-dd" style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日甲方和乙方共同签订的 <input style="border-bottom: 1px dashed black;" v-model="agreementData.contractPeriod"
                        :disabled="isView">
                    期限的劳动合同，现经甲方提出，双方协商一致确定于
                    <el-date-picker v-model="agreementData.endDate" type="date" :disabled="isView"
                        value-format="yyyy-MM-dd" style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日解除劳动合同。
                </p>
            </div>
            <div class="clause">
                <p style=" text-indent: 2em ;">二、乙方同意甲方一次性支付劳动关系解除的经济补偿金等各项费用共计人民币<input
                        style="border-bottom: 1px dashed black;" v-model="agreementData.compensationAmount"
                        :disabled="isView"> 元（大写：<input style="border-bottom: 1px solid black;"
                        v-model="agreementData.chineseAmount" :disabled="isView"> 元）。 </p>
            </div>
            <div class="clause">
                <p style=" text-indent: 2em ;">三、上述费用付清后，乙方自愿放弃基于双方劳动关系发生及解除所产生的其他各项权利；</p>
            </div>
            <div class="clause">
                <p style=" text-indent: 2em ;">四、本协议一式两份，自双方签章之日起生效。</p><br>
            </div>
            <div class="signature-group">
                <div class="form-group">
                    <label style="font-weight: bold;">甲方（签章）：</label>
                    <input style="width: 20%;" v-model="agreementData.asignature" :disabled="isView">
                    <label style="font-weight: bold;">&emsp;&emsp;&emsp;乙方签名（盖手印）：</label>
                    <input style="width: 20%;" v-model="agreementData.bsignature" :disabled="isView">
                </div>
            </div>
            <div class="date-group">
                <div class="form-group">
                    <label>甲方签署日期：</label>
                    <el-date-picker v-model="agreementData.asignDate" type="date" :disabled="isView"
                        value-format="yyyy-MM-dd" style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    <label>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;乙方签署日期：</label>
                    <el-date-picker v-model="agreementData.bsignDate" type="date" :disabled="isView"
                        value-format="yyyy-MM-dd" style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                </div>
            </div>
            <div class="footer">
                <p style="display: flex;justify-content: space-between;font-size: 18px;color: #757575;">
                    <span>表单编号及版本：AM-JY-276 A/0 </span><span>保存期限：长期</span>
                </p>
            </div>
        </div>
    </div>
</template>

<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { getLaborTerminationById, saveLaborTermination } from '@/api/laborTermination'

export default {
    data() {
        return {
            isView: false,
            agreementData: {
                id: null,
                aparty: '',
                bparty: '',
                idNumber: '',
                startDate: '',
                contractPeriod: '',
                endDate: '',
                compensationAmount: '',
                chineseAmount: '',
                asignature: '',
                bsignature: '',
                asignDate: '',
                bsignDate: ''
            }
        }
    },
    watch: {
        'agreementData.compensationAmount': {
            handler(newVal) {
                if (newVal) {
                    this.agreementData.chineseAmount = this.numberToChinese(newVal)
                } else {
                    this.agreementData.chineseAmount = ''
                }
            }
        }
    },
    created() {
        const { id, type } = this.$route.query
        if (id) {
            this.fetchData(id)
        }
        this.isView = type === 'view'
    },
    methods: {
        numberToChinese(num) {
            if (isNaN(num)) return ''
            const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
            const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿']
            const decimal = ['角', '分']

            // 分割整数和小数部分
            let [integer, decimal_part = ''] = num.toString().split('.')
            let chineseStr = ''

            // 处理整数部分
            if (integer !== '0') {
                for (let i = 0; i < integer.length; i++) {
                    const digit = parseInt(integer[i])
                    const unit = units[integer.length - 1 - i]
                    if (digit !== 0) {
                        chineseStr += digits[digit] + unit
                    } else {
                        if (i < integer.length - 1 && integer[i + 1] !== '0') {
                            chineseStr += '零'
                        }
                    }
                }
                chineseStr += '元'
            }

            // 处理小数部分
            if (decimal_part) {
                decimal_part = decimal_part.padEnd(2, '0').substr(0, 2)
                for (let i = 0; i < 2; i++) {
                    const digit = parseInt(decimal_part[i])
                    if (digit !== 0) {
                        chineseStr += digits[digit] + decimal[i]
                    }
                }
            } else {
                chineseStr += '整'
            }

            return chineseStr
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/xsjiechuyi/xsjiechuyiList')
        },
        goBack() {
            this.$router.push('/main/renshi/renshizhidu')
        },
        fetchData(id) {
            getLaborTerminationById(id).then(response => {
                this.agreementData = response.data
            })
        },
        validateIdNumber(idNumber) {
            // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
            const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
            return reg.test(idNumber)
        },
        validateForm() {
            if (!this.agreementData.bparty) {
                this.$message({
                    type: 'warning',
                    message: '请输入乙方姓名'
                })
                return false
            }
            if (!this.agreementData.idNumber) {
                this.$message({
                    type: 'warning',
                    message: '请输入身份证号码'
                })
                return false
            }
            if (!this.validateIdNumber(this.agreementData.idNumber)) {
                this.$message({
                    type: 'warning',
                    message: '请输入正确的身份证号码格式'
                })
                return false
            }
            if (!this.agreementData.startDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择合同开始日期'
                })
                return false
            }
            if (!this.agreementData.endDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择合同解除日期'
                })
                return false
            }
            if (!this.agreementData.asignDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择甲方签署日期'
                })
                return false
            }
            if (!this.agreementData.bsignDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择乙方签署日期'
                })
                return false
            }
            return true
        },
        saveData() {
            if (!this.validateForm()) {
                return
            }
            const data = {
                ...this.agreementData
            }
            saveLaborTermination([data]).then(() => {
                this.$message({
                    type: 'success',
                    message: '保存成功！'
                })
                this.$router.push('/main/renshi/renshizhidu/xsjiechuyi/xsjiechuyiList')
            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '保存失败：' + error.message
                })
            })
        },
        printToPDF() {
            const doc = new jsPDF('p', 'pt', 'a4');
            const element = document.querySelector('.agreement-wrapper');
            html2canvas(element).then((canvas) => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 522;
                const pageHeight = 841.89;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                let positionY = 0;
                if (imgHeight >= pageHeight) {
                    let leftHeight = imgHeight;
                    while (leftHeight >= pageHeight) {
                        doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, pageHeight);
                        positionY += pageHeight;
                        doc.addPage();
                        leftHeight -= pageHeight;
                    }
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, leftHeight);
                } else {
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight);
                }
                doc.save('协商解除劳动合同协议书一.pdf');
            });
        },
        printForm() {
            window.print();
        },
    }
};
</script>

<style scoped>
/* ::v-deep .el-input__prefix {
    height: 100%;
    left: -30px;
    transition: all .3s;
}

::v-deep .el-input__prefix,
.el-input__suffix {
    position: absolute;
    top: 10px;
    text-align: center;
} */

.agreement-wrapper {
    width: 100%;
    margin-top: 20px;
}

.form-group {
    margin-bottom: 10px;
}

.clause {
    margin-bottom: 15px;
}

.footer {
    text-align: center;
    margin-top: 20px;
}

input {
    border: 0px;
}

.el-date-picker {
    border: none;
    border-bottom: 1px dashed black;
}

/* 
button {
    padding: 5px 10px;
    margin: 0px 10px 10px 10px;
} */
@media print {
    .el-button {
        display: none;
    }

    ::v-deep .el-input--prefix .el-input__inner {
        border: none;
        font-family: '宋体';
        font-size: 18px;
        color: #2C3E50;
        padding-left: -30px;
    }

    ::v-deep .el-input__icon {
        display: none;
    }
}
</style>